package com.bootcamp.javase2.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @program: IOCode
 * @description: copy an image with single byte or byte array.
 * @author: Keyu Li
 * @create: 2021-09-09 20:29
 **/

public class IOImageCopy {
    public static void main(String[] args) throws IOException {
        // check file
        String src = "IO_Image.png";
        String dstSingleImage = "IO_Image_single_copy.png";
        String dstBytesImage = "IO_Image_bytes_copy.png";
        String dstSingleTxt = "IO_Image_single.txt";
        String dstBytesTxt = "IO_Image_bytes.txt";
        File srcf = new File(src);
        if (!srcf.exists()) return;

        //set time
        long snap1 = System.currentTimeMillis();
        //copy to image
        // single byte copy
        singleByteCopy(src, dstSingleImage);
        bytesArrayCopy(src, dstBytesImage);
        long snap2 = System.currentTimeMillis();
        System.out.println("copy to image time cost: " + (snap2 - snap1));

        //copy to text
        singleByteCopy(src, dstSingleTxt);
        bytesArrayCopy(src, dstBytesTxt);
        snap1 = System.currentTimeMillis();
        System.out.println("copy to text time cost: " + (snap1 - snap2));
//        PrintFile.print(dstBytesTxt);

    }

    private static void singleByteCopy(String src, String dst) throws IOException {
        FileInputStream in = new FileInputStream(src);
        FileOutputStream out = new FileOutputStream(dst);
        int readData;
        while ((readData = in.read()) != -1) {
            out.write(readData);
        }
        //close
        in.close();
        out.close();
    }

    private static void bytesArrayCopy(String src, String dst) throws IOException {
        byte[] bytes = new byte[2048];
        FileInputStream in = new FileInputStream(src);
        FileOutputStream out = new FileOutputStream(dst);
        int readCount;
        while ((readCount = in.read(bytes)) != -1){
            out.write(bytes);
        }
        //close
        in.close();
        out.close();
    }
}
